<template>
	<view class="fqq-form">

		<Navbar title="申请" bgColor="#fff" :h5Show="false" :autoBack="true" :border="true" :onpageshow="false">
		</Navbar>

		<view class="details">
			<u-toast ref="uToast" />
			<view class="herder-form">
				<view class="herder-form-title">
					<view class="title">有房就能申请 最快1天到账</view>
				</view>
				<image src="@/static/fqq-img/bg2.png" mode="aspectFill"></image>
				<view class="form-date">
					<u-form :model="formData" ref="uForm" style="margin: 0 1.5rem;">
						<!-- <u-form-item label="姓名"><u-input v-model="form.fullName" /></u-form-item> -->
						<!-- <u-form-item label="真实姓名" label-width="140" prop="fullName">
						<u-input v-model="formData.fullName" style="width: 100%; pointer-events: auto;" focus="true" />
					</u-form-item> -->
						<u-form-item label="真实姓名" label-width="140" prop="fullName" ref="fullName">
							<u-input v-model="formData.fullName" style="width: 100%; pointer-events: auto;"
								placeholder="请输入" />
						</u-form-item>
						<u-form-item label="手机号码" label-width="140" prop="phone" ref="phone">
							<u-input v-model="formData.phone" :disabled="statusType != 1" placeholder="请输入" />
						</u-form-item>
						<u-form-item label="所在城市" label-width="140" @click="openPoup()" prop="provinceCity"
							ref="provinceCity">
							<u-input readonly v-model="formData.provinceCity" placeholder="请选择"
								style="pointer-events:none" />
							<!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
						</u-form-item>
						<u-picker ref="uPicker" :show="show" :columns="addressColumns" :defaultIndex="areaDetault"
							:closeOnClickOverlay="true" @confirm="nationSel($event, 'area')" @cancel="show = false"
							@close="show = false" @change="changeHandler">
						</u-picker>
						<!-- 所需额度 -->

						<u-form-item label="所需额度" label-width="140" @click="showAmountPicker = true" prop="quota">
							<u-input readonly v-model="formData.quota" placeholder="请选择" style="pointer-events:none" />
						</u-form-item>
						<u-picker :show="showAmountPicker" :columns="[amountOptions]" @confirm="amountConfirm"
							@close="showAmountPicker = false" :closeOnClickOverlay="true">
						</u-picker>

						<u-form-item label="房产市值" label-width="140" @click="openPropertyPicker('marketValue')"
							prop="marketValue">
							<u-input readonly v-model="formData.marketValue" placeholder="请选择"
								style="pointer-events:none" />
						</u-form-item>

						<!-- 房屋类型 -->
						<u-form-item label="房屋类型" label-width="140" @click="openPropertyPicker('houseType')"
							prop="houseType">
							<u-input readonly v-model="formData.houseType" placeholder="请选择"
								style="pointer-events:none" />
						</u-form-item>

						<!-- 房产情况 -->
						<u-form-item label="房产情况" label-width="140" @click="openPropertyPicker('propertySituation')"
							prop="propertySituation">
							<u-input readonly v-model="formData.propertySituation" placeholder="请选择"
								style="pointer-events:none" />
						</u-form-item>
						<u-picker :show="showPropertyPicker" :columns="[propertyOptions[currentPropertyType]]"
							@confirm="propertyConfirm" @close="showPropertyPicker = false" :closeOnClickOverlay="true">
						</u-picker>
						<!-- <view style="font-size: 15px; margin-top: 1rem">车牌号码</view>
						<u-form-item prop="carNum" ref="carNum">
							<CarKeyBoard v-model='formData.carNum'></CarKeyBoard>
						</u-form-item>
						<view style="font-size: 15px; margin-top: 1rem">购车方式</view>
						<u-form-item style="margin-top:8px ;" prop="radioSelect" ref="radioSelect">
							<u-input v-model="formData.radioSelect" style="display: none;" />
							<view class="radio-chang" v-for="(item, index) in radioItem">
								<view :class="radioSelectId == item.id ? 'radio-chang-item' : 'radio-item'"
									:value="item.value" @click="radioChang(item)" :key="item.id">{{ item.value }}</view>
							</view>
						</u-form-item> -->
					</u-form>
					<view style="margin-top: 4vh;">
						<button class="subimt-but" @click="submit()"
							style="background-color: #3342ff; color: #fff;width: 90%;">立即申请</button>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
import {
	postSaveInfo,
	getLoanInfoAdmin,
	Verification
} from "@/api/api.js"
import areaData from '@/utils/pac.json'
import Navbar from '@/components/navbar/Navbar'
export default {
	components: {
		Navbar
	},
	data() {
		return {
			isPaymentBtn: false,
			id: '',
			details: {},
			formData: {
				fullName: '',
				phone: '',
				provinceCity: '',
				city: '',
				quota: '', // 购车方式
				marketValue: '', // 房产市值
				houseType: '',     // 房屋类型
				propertySituation: '' // 房产情况
			},
			amountOptions: [
				'5万-10万',
				'10万-15万',
				'15万-20万',
				'20万-50万'
			],
			propertyOptions: {
				// 房产市值选项
				marketValue: [
					'50万-100万',
					'100万-200万',
					'200万-500万',
					'500万以上'
				],
				// 房屋类型选项
				houseType: [
					'商品房',
					'公寓',
					'商铺',
					'别墅',

				],
				// 房产情况选项
				propertySituation: [
					'名下全款有证',
					'名下按揭有证'
				]
			},
			showPropertyPicker: false,
			currentPropertyType: '', // 当前选择的房产字段类型
			showAmountPicker: false,
			serverType: '',
			show: false,
			params: {
				province: true,
				city: true,

			},
			radioItem: [{
				label: '全款',
				value: '全款',
				id: '1',
			},
			{
				label: '分期已结清',
				value: '分期已结清',
				id: '2',
			},
			{
				label: '分期未结清',
				value: '分期未结清',
				id: '3',
			}
			],
			rules: {
				// 字段名称
				fullName: [{
					required: true,
					message: '请填写姓名',
					trigger: ['change', 'blur']
				},

				],
				phone: [{
					required: true,
					message: '请填写手机号',
					trigger: ['change', 'blur']
				},

				],
				provinceCity: [{
					required: true,
					message: '请选择城市',
					trigger: ['change', 'blur']
				},

				],
				quota: [{
					required: true,
					message: '请选择所需额度',
					trigger: ['change', 'blur']
				}],
				marketValue: [{
					required: true,
					message: '请选择房产市值',
					trigger: ['change', 'blur']
				}],
				houseType: [{
					required: true,
					message: '请选择房屋类型',
					trigger: ['change', 'blur']
				}],
				propertySituation: [{
					required: true,
					message: '请选择房产情况',
					trigger: ['change', 'blur']
				}]




			},
			system: null,
			statusType: '',
			areaData: areaData,    //原始数据
			addressColumns: [],  //数据数组
			areaDetault: [],    //数据回显时的默认数据

		};
	},
	onLoad(option) {
		this.system = uni.getSystemInfoSync();
		// this.verification()
		// this.id = JSON.parse(option.details).id
		// this.getDetails()
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
		this.formData.phone = uni.getStorageSync('phone')
	},
	created() {

	},
	methods: {

		openPropertyPicker(type) {
			this.currentPropertyType = type;
			this.showPropertyPicker = true;
		},

		// 房产信息确认
		propertyConfirm(e) {
			this.formData[this.currentPropertyType] = e.value[0];
			this.showPropertyPicker = false;
		},

		amountConfirm(e) {
			this.formData.quota = e.value[0]
			this.showAmountPicker = false
		},

		openPoup() {
			this.areaDetault = [0, 0];
			this.show = true;
			this.getAreaList();
		},

		getAreaList() {
			//省的数组
			const provinceData = this.areaData.map(e => {
				return e.name
			})
			//市的数组
			const cityData = this.areaData.map(e => {
				const arr = []
				arr.push(
					e.children.map(c => {
						return c.name
					})
				)
				return arr
			})
			const arr = [provinceData, cityData[0][0]] //组装
			this.addressColumns = arr
		},

		// 选中时执行
		changeHandler(e) {
			const { columnIndex, index, indexs, picker = this.$refs.uPicker } = e
			if (columnIndex === 0) {
				const children1 = this.areaData[index].children.map(e => {
					return e.name
				})
				picker.setColumnValues(1, children1)
			}
			if (columnIndex === 1) {
				const children3 = this.areaData[indexs[0]].children[indexs[1]].children.map(e => {
					return e.name
				})
			}
		},

		// 根据回显数据设置默认选中项
		setDefault() {
			// 户籍所在地
			let temp = []
			temp = this.model.address.split('/')
			let index, index1 = 0
			let arr, arr1 = []
			//市区对应每列的第几个
			this.areaData.forEach((item, i) => {
				if (item.name == temp[0]) {
					index = i
					item.children.forEach((val, ind) => {
						if (val.name == temp[1]) {
							index1 = ind
						}
					})
				}
			})
			//匹配省市区对应每列的第几个
			arr = this.areaData.map(e => {
				return e.name
			})
			arr1 = this.areaData[index].children.map(e => {
				return e.name
			})
			this.addressColumns = [arr, arr1]
			this.areaDetault = [index, index1]
		},
		// 选择框确认按钮（有多个选择器时用type进行判断）
		nationSel(event, type) {
			let value = event.value
			this.formData.provinceCity = value[1];
			this.formData.address = value.join('/');
			this.show = false
		},


		// async verification() {
		// 	let res = await Verification({
		// 		marketValue: this.system.model
		// 	})
		// 	this.statusType = res.data.status
		// 	this.formData.phone = this.statusType != 1 ? uni.getStorageSync('phone') : null
		// },
		// changeHandler(e) {
		// 	const {
		// 		columnIndex,
		// 		value,
		// 		values, // values为当前变化列的数组内容
		// 		index,
		// 		// 微信小程序无法将picker实例传出来，只能通过ref操作
		// 		picker = this.$refs.uPicker
		// 	} = e
		// 	// 当第一列值发生变化时，变化第二列(后一列)对应的选项
		// 	if (columnIndex === 0) {
		// 		// picker为选择器this实例，变化第二列对应的选项
		// 		picker.setColumnValues(1, this.columnData[index])
		// 	}
		// },
		// 回调参数为包含columnIndex、value、values
		confirm(e) {
			this.show = false
		},
		// nationSel(res) {
		// 	this.formData.provinceCity = res.province.label + '-' + res.city.label
		// 	this.formData.city = res.city.label
		// },


		IsCarOfOld(value) {
			const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z][A-HJ-NP-Z0-9]{5}$/;
			const xreg =
				/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z]((?:[DF][A-HJ-NP-Z0-9]\d{4})|(?:\d{5}[DF]\d{2}))$/;
			console.log("xreg.test(value)", value, value.length === 7, creg.test(value))
			if (value.length == 7) {
				if (!creg.test(value)) {
					uni.showToast({ title: '请输入正确格式的车牌号', icon: 'none' });
					return;
				}

			} else if (value.length == 8) {
				if (!xreg.test(value)) {
					uni.showToast({ title: '请输入正确格式的车牌号', icon: 'none' });
					return;
				}

			}



			// if (value.length === 8) {
			// 	return xreg.test(value);
			// } else {
			// 		this.$refs.uToast.show({
			// 			title: '请输入正确格式的车牌号',
			// 		})
			// 	return false;
			// }
		},


		// 测试
		// console.log(validatePlateNumber("粤B12345"));   // true (油车)
		// console.log(validatePlateNumber("粤AD12345"));  // true (新能源)
		// console.log(validatePlateNumber("粤A1234A"));   // false (不合法)

		async submit() {
			this.$refs.uForm.validate().then(async valid => {// 添加 async

				if (valid) {
					try {
						// 添加 await 并处理响应
						const res = await postSaveInfo({
							phone: this.formData.phone,
							name: this.formData.fullName,
							city: this.formData.provinceCity,
							quota: this.formData.quota,
							marketValue: this.formData.marketValue,
							houseType: this.formData.houseType,
							propertySituation: this.formData.propertySituation,
							deviceBrand: this.system.deviceBrand ? this.system.deviceBrand : this.system.model,
						});
						if (res.code == 200) {  // 明确判断成功状态
							uni.showToast({
								title: '申请成功，后面会有客服联系您！请注意接听',
								icon: 'none'
							});

							this.formData = {}
							// 跳转到/pages/index/index
							uni.switchTab({  // ← 改用switchTab（如果首页是tabbar页面）
								url: '/pages/index/index'
							})



						} else {
							uni.showToast({
								title: res.msg || '提交失败',
								icon: 'none'
							});
						}
					} catch (error) {
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
				} else {
					console.log('验证失败');
					uni.showToast({
						title: '请填写完整表单信息',
						icon: 'none'
					});
				}
			});
		}

	}
};
</script>

<style scoped lang="scss">
.details {
	width: 100%;
	height: calc(100vh - 0rpx);
	background-color: #fbfbfb;

	// padding: 50rpx;
	.detailsBox {
		// width: 100%;
		// height: 100%;
		background-color: #fff;
		border-radius: 20rpx;
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		padding: 30rpx;

		.item {
			margin: 40rpx;
			font-size: 30rpx;
			vertical-align: middle;
			// font-weight: bold;
		}
	}
}

.paymentBtn {
	text-align: center;
	line-height: 80upx;
	height: 80upx;
	background-color: #F3DEA0;
	border-radius: 80upx;
	// margin: 50upx 0;
	margin-top: 100rpx;
	margin-bottom: 50rpx;
}

.paymentBtnH {
	color: #fff;
	background-color: #ccc !important;

}

.herder-form {
	// border: 1px solid red;
	width: 100%;
	height: 30%;

	image {
		// border-radius: 10rpx;
		width: 100%;
		height: 100%;
	}

	.herder-form-title {
		// font-size: 20px;
		text-align: center;
		/* padding-top: 28px; */
		position: absolute;
		top: 5rem;
		left: 50%;
		width: 100%;
		transform: translateX(-50%);
		color: aliceblue;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9;

		.title {
			font-size: 45rpx;
			text-align: center;
			color: #ffffffb8;
		}
	}

	.form-date {
		// border: 1px solid red;
		height: 50vh;
		position: absolute;
		top: 18vh;
		width: 96%;
		background-color: #fff;
		left: 2%;
		border-radius: 2%;
	}
}

.radio-chang {
	display: flex;
	margin-right: 1rem;

	.radio-item {
		border-radius: 8px;
		border: 1px solid #dedada;
		padding: 2px 5px;
	}

	.radio-chang-item {
		border-radius: 8px;
		border: 1px solid #3342ff;
		padding: 2px 5px;
		width: 100%;
		color: #3342ff;
	}

	::v-deep .u-toast__text {
		color: #3342ff;
		/* 更改字体颜色 */
	}
}
</style>
